package com.jiang.controller;

import com.jiang.bean.Song;
import com.jiang.exception.PermissionOrRoleException;
import com.jiang.service.SongService;
import com.jiang.utils.AjaxResult;
import com.jiang.utils.DebugUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * Created by dllo on 18/4/13.
 */
@Controller
public class SongController {
    @Resource
    private SongService songService;

    @ResponseBody
    @RequestMapping(value = "/getsongs")
    public AjaxResult getSongs(@RequestParam(value = "songname") String songName) {
        System.out.println(songName);
        try {
            return songService.getInternetSong(songName);
        }catch (Exception e){

            e.printStackTrace();
            return null;
        }
    }


    @RequestMapping(value = "/downloadMusic")
    public void download(@RequestParam(value = "songName") String songName,
                         @RequestParam(value = "songId") String songId,
                         HttpServletResponse response,
                         HttpServletRequest request) {
        String url = "http://link.hhtjim.com/kw/" + songId;
        try {
            songService.downloadMusic(songName, url, response);
        } catch (IOException e) {
            DebugUtil.sout("用户取消下载");
        } catch (PermissionOrRoleException e) {
            DebugUtil.sout("没有下载权限");
            try {
                request.getRequestDispatcher("/WEB-INF/nopermission.html").forward(request, response);
            } catch (ServletException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    @ResponseBody
    @RequestMapping(value = "/searchInner")
    public AjaxResult searchInner(@RequestParam(value = "songName") String songName){
        List<Song> songList = songService.searchInner(songName);
        return AjaxResult.getOk(songList);
    }

}
